<?php

namespace App\Http\Controllers\Api;

use App\Events\Money\ConsumeEvent;
use App\Events\Ticket\BuyEvent;
use App\Facades\Snowid;
use App\Http\Controllers\Common\Internal;
use App\Models\ChargeProduct;
use App\Models\LoanApplication;
use App\Models\LoanApplicationLog;
use App\Models\LoanTag;
use App\Models\Order;
use App\Models\UserInvite;
use App\Models\UserKyc;
use App\Models\UserMoneyLog;
use App\Models\UserMoneyWithdraw;
use App\Models\User;
use App\Models\UserTicketLog;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;


class UserController extends BaseController
{

    /**
     * 实名认证信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function kyc(Request $request) {
        $user = $request->user();

        if($user->kycInfo){
            $user->kycInfo->address_tag = $user->kycInfo->address_tag ? json_decode($user->kycInfo->address_tag) : [];
        }
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'kyc_info' => $user->kycInfo,
                'kyc_status' => $user->kyc,
                'kyc_name' => $user->kyc_name
            ]
        ]);
    }

    /**
     * 实名认证申请
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function saveKyc(Request $request) {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'realname' => 'required',
            'idcard' => 'required',
            'image_face' => 'required|url',
            'image_back' => 'required|url',
        ], [
            'required' => ':attribute 必填',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $user = $request->user();
        if ($user->kyc == 1) {
            return response()->json([
                'code' => 1,
                'msg' => '您已经申请认证，请等待审核',
                'data' => null
            ]);
        }
//        else if ($user->kyc == 2) {
//            return response()->json([
//                'code' => 1,
//                'msg' => '您认证已经通过',
//                'data' => null
//            ]);
//        }

        $model = UserKyc::where('user_id', $request->user()->id)->first();

        if(empty($model)) $model = new UserKyc();

        $model->mobile = $request->mobile;
        $model->realname = $request->realname;
        $model->idcard = $request->idcard;
        $model->image_face = $request->image_face;
        $model->image_back = $request->image_back;
        $model->user_id = $request->user()->id;
        $model->address_tag = json_encode($request->tags,JSON_UNESCAPED_UNICODE);

        $user->kyc = 1;
        if ($model->save() && $user->save()) {
            return response()->json([
                'code' => 0,
                'msg' => '提交成功',
                'data' => null
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '提交失败',
                'data' => null
            ]);
        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function account(Request $request) {
        $user = $request->user();

        $now = Carbon::now();

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'name' => $user->name,
                'money' => $user->money,
                'ticket' => $user->ticket,
                'kyc' => $user->kyc,
                'day' => $now->diffInDays(new Carbon($user->created_at))
            ]
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function myInvite(Request $request) {
        $pageSize = (int) $request->input('pageSize', 20);
        $page = (int) $request->input('page', 1);
        $user = $request->user();

        $parentData = [];
        if($user->parent_id){
            $parentUser =  User::where('id',$user->parent_id)->first();
            if($parentUser){
                $parentData['name'] =$parentUser->name;
                $parentData['mobile'] =$parentUser->mobile;
            }
        }

        $query = UserInvite::with('child')->where('user_id', $user->id)->orderByDesc('id');

        $user_id = $user->id;
        $child_ids = User::where('parent_id',$user_id)->pluck('id')->toArray();
        $team_ticket = UserTicketLog::where('category',1)->whereIn('user_id',$child_ids)->sum('ticket');




        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $data[] = [
                'name' => $v->child->name,
                'ticket' => $v->child->ticket,
                'money' => $v->child->money,
                'phone' => $v->child->mobile,
                'kyc' => $v->child->kyc,
                'kyc_name' => $v->child->kyc_name,
                'created_at' => $v->child->created_at->format('Y/m/d H:i'),
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'parentData'=>$parentData,
                'items' => $data,
                'team_ticket' => $team_ticket,
                'invite_count' => $user->invite_count,
            ]
        ]);
    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function inviteCode(Request $request) {

        $user = $request->user();
        if (!empty($user->invite_code)) {
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'code' => $user->invite_code
                ]
            ]);
        }

        $user->invite_code = Str::random(8);
        if ($user->save()) {
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'code' => $user->invite_code
                ]
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => 'failed',
                'data' => null
            ]);
        }
    }

    /**
     * 分享图片
     *
     * @param Request $request
     * @return mixed
     */
    public function inviteImage(Request $request) {

        $img = Image::make(public_path('images/share-bg.png'));

        $qr_str = $request->input('qr');
        $qr = Image::make($qr_str);

        $img->insert($qr, '', 273, 1043);

//        $response = Response::make($img->encode('png'));
//        // set content-type
//        $response->header('Content-Type', 'image/png');
//
//        // output
//        return $response;

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => (string) $img->encode('data-url')
        ]);
    }

    /**
     * 贷款物料列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function loan(Request $request) {
        $pageSize = (int) $request->input('pageSize', 20);

        $user = $request->user();

        $query = LoanApplication::with('tags')->where('user_id', $user->id)->orderByDesc('id');

        if ($category = $request->category) {
            $query->where('category', $category);
        }

        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $tags = [];
            foreach ($v->tags as $tag) {
                $tags[] = [
                    'id' => $tag->id,
                    'title' => $tag->title,
                ];
            }

            $data[] = [
                'id' => $v->id,
                'name' => $v->name,
                'number' => $v->number,
                'amount_start' => $v->amount_start,
                'amount_start_zh' => $v->amount_start_zh,
                'amount_end' => $v->amount_end,
                'amount_end_zh' => $v->amount_end_zh,
                'need_home_service' => $v->need_home_service,
                'province' => $v->province,
                'city' => $v->city,
                'apply_at' => $v->apply_at,
                'category' => $v->category,
                'need_ticket' => Internal::getNeedTicket($v->category_type, $v->province,$v->id),
                'category_type' => $v->category_type,
                'category_name' => $v->custom_field??$v->category_name,
                'status_name' => $v->status_name,
                'tags' => $tags
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $data,
            ]
        ]);
    }


    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function loanDetail(Request $request, $id)
    {
        $user = $request->user();
        $loan = LoanApplication::with(['creditProvident', 'mortgageCar', 'mortgageHouse', 'mortgageTax'])
            ->where('user_id', $user->id)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        } else {
            $tags = [];
            foreach ($loan->tags as $v) {
                $tags[] = [
                    'id' => $v->id,
                    'title' => $v->title,
                ];
            }

            $logModels = LoanApplicationLog::with("user")
                ->where('loan_id', $id)
                ->orderByDesc('id')->limit(5)->get();
            $logs = [];
            foreach ($logModels as $v) {
                $logs[] = [
                    'user_name' => $v->user->name,
                    'comment' => $v->comment,
                    'created_at' => $v->created_at->format('Y/m/d H:i'),
                ];
            }
            $zhima = "无";
            if($loan->zhima == 2){
                $zhima = '600分以下';
            }elseif ($loan->zhima == 3){
                $zhima = '600-650分';
            }elseif ($loan->zhima == 4){
                $zhima = '650-700分';
            }elseif ($loan->zhima == 5){
                $zhima = '大于700';
            }
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'id' => $loan->id,
                    'name' => $loan->name,
                    'status' => $loan->status,
                    'number' => $loan->number,
                    'amount_start' => $loan->amount_start,
                    'amount_start_zh' => $loan->amount_start_zh,
                    'amount_end' => $loan->amount_end,
                    'amount_end_zh' => $loan->amount_end_zh,
                    'need_home_service' => $loan->need_home_service,
                    'province' => $loan->province,
                    'channel_name' => $loan->channel_name,
                    'city' => $loan->city,
                    'refund_msg' => $loan->refund_msg,
                    'apply_at' => $loan->apply_at,
                    'category' => $loan->category,
                    'need_ticket' => Internal::getNeedTicket($loan->category_type, $loan->province,$loan->id),
                    'category_type' => $loan->category_type,
                    'category_name' => $loan->category_name,
                    'has_house' => Internal::getDataPQ($loan->has_house),
                    'has_car' => Internal::getDataPQ($loan->has_car),
                    'has' => Internal::getDataPQ($loan->has),
                    'yingyezhizhao' => Internal::getDataPQ($loan->yingyezhizhao),
                    'has_gongjijin' => Internal::getDataPQ($loan->has_gongjijin),
                    'zhima' => $zhima,
                    'tags' => $tags,
                    'logs' => $logs,
                    'profile' => [
                        'company_name' => $loan->creditProvident ?  $loan->creditProvident->company_name : '-',
                        'pay_method' => $loan->creditProvident ?  $loan->creditProvident->pay_method : '-',
                        'month_salary' => $loan->creditProvident ?  $loan->creditProvident->month_salary : '-',
                        'provident_age' => $loan->creditProvident ?  $loan->creditProvident->provident_age : '-',
                        'month_provident' => $loan->creditProvident ?  $loan->creditProvident->month_provident : '-',
                    ],
                    'house' => [
                        'type' => $loan->mortgageHouse ?  $loan->mortgageHouse->type : '-',
                        'has_certificate' => $loan->mortgageHouse ?  ($loan->mortgageHouse->has_certificate ? '是' : '否') : '-',
                        'ownership' => $loan->mortgageHouse ?  ($loan->mortgageHouse->ownership ? '是' : '否') : '-',
                        'latest_estimated' => $loan->mortgageHouse  ? $loan->mortgageHouse->latest_estimated : '-',
                    ],
                    'car' => [
                        'info' => $loan->mortgageCar ?  $loan->mortgageCar->info : '-',
                        'car_model' => $loan->mortgageCar ?  $loan->mortgageCar->car_model : '-',
                        'car_price_estimation' => $loan->mortgageCar ?  $loan->mortgageCar->car_price_estimation : '-',
                        'buy_price' => $loan->mortgageCar && $loan->mortgageCar->buy_price > 0 ?  toZhNum($loan->mortgageCar->buy_price) : '-',
                        'car_no' => $loan->mortgageCar ?  $loan->mortgageCar->car_no : '-',
                    ],
                    'company' => [
                        'annal_tax' => $loan->mortgageTax  ?  $loan->mortgageTax->annal_tax : '-',
                        'annal_turnover' => $loan->mortgageTax   ?  $loan->mortgageTax->annal_turnover : '-',
                        'company_age' => $loan->mortgageTax ?  $loan->mortgageTax->company_age : '-',
                        'is_legal_person' => $loan->mortgageTax ?  ($loan->mortgageTax->is_legal_person ? '是' : '否') : '-',
                    ],
                ]
            ]);
        }
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function loanTelephone(Request $request, $id) {
        $user = $request->user();
        $loan = LoanApplication::ofOwner($user)->find($id);
        if (empty($loan)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => null
            ]);
        } else {
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => $loan->mobile
            ]);
        }
    }


    /**
     * 资金流水
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function logMoney(Request $request) {

        $pageSize = (int) $request->input('pageSize', 20);
        $user = $request->user();

        $query = UserMoneyLog::where('user_id', $user->id)->orderByDesc('id');

        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $data[] = [
                'money' => $v->money,
                'comment' => $v->comment,
                'category' => $v->category,
                'category_name' => $v->category_name,
                'created_at' => $v->created_at->format('Y年m月d日 H:i'),
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $data,
                'total' => $user->money,
            ]
        ]);
    }

    /**
     * 次数流水
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function logTicket(Request $request) {

        $pageSize = (int) $request->input('pageSize', 20);
        $user = $request->user();

        $query = UserTicketLog::where('user_id', $user->id)->orderByDesc('id');

        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $data[] = [
                'ticket' => $v->ticket,
                'comment' => $v->comment,
                'category' => $v->category,
                'category_name' => $v->category_name,
                'created_at' => $v->created_at->format('Y年m月d日 H:i'),
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $data,
                'total' => $user->ticket,
            ]
        ]);
    }

    /**
     * 用户的标签
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function tag(Request $request)
    {
        $user = $request->user();

        $tags = LoanTag::ofOwner($user)->select(["id","title"])->get();

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $tags,
            ]
        ]);
    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function saveTag(Request $request) {
        if (empty($request->title)) {
            return response()->json([
                'code' => 1,
                'msg' => '名称不能为空',
                'data' => null
            ]);
        }

        $user = $request->user();
        $model = LoanTag::ofOwner($user)->where('title', $request->title)->first();
        if(!empty($model)) {
            return response()->json([
                'code' => 0,
                'msg' => 'duplicate',
                'data' => [
                    'id' => $model->id,
                    'title' => $model->title,
                ]
            ]);
        }

        $model = new LoanTag();
        $model->title = $request->title;
        $model->org_root = 200;
        if (!empty($user->org_code)) {
            $model->org_code = $user->org_code;
        }
        $model->user_id = $user->id;

        if ($model->save()) {
            return response()->json([
                'code' => 0,
                'msg' => 'ok',
                'data' => [
                    'id' => $model->id,
                    'title' => $model->title,
                ]
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '保存失败',
                'data' => null
            ]);
        }
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function withdrawList(Request $request) {
        $pageSize = (int) $request->input('pageSize', 20);
        $user = $request->user();

        $query = UserMoneyWithdraw::where('user_id', $user->id)->orderByDesc('id');

        /* @var $pages \Illuminate\Contracts\Pagination\LengthAwarePaginator */
        $pages = $query->simplePaginate($pageSize);

        $data = [];
        foreach ($pages->items() as $v) {
            $data[] = [
                'money' => $v->money,
                'comment' => $v->comment,
                'status' => $v->status,
                'status_name' => $v->status_name,
                'created_at' => $v->created_at->format('Y年m月d日 H:i'),
            ];
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $data,
            ]
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function money(Request $request) {
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'money' => $request->user()->money,
                'free_money' => $request->user()->free_money,
                'ticket' => $request->user()->ticket,
            ]
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function processingWithdraw(Request $request) {
        $items = UserMoneyWithdraw::where('user_id', $request->user()->id)
            ->where('status', UserMoneyWithdraw::PROCESSING)
            ->orderByDesc('id')
            ->get();

        $data = [];
        foreach ($items as $v) {
            $data[] = [
                'money' => $v->money,
                'comment' => $v->comment,
                'status' => $v->status,
                'status_name' => $v->status_name,
                'created_at' => $v->created_at->format('Y年m月d日 H:i'),
            ];
        }
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => $data
            ]
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function withdraw(Request $request) {
        $withdraw_money = intval(floatval($request->money) * 100);
        if ($withdraw_money < 10000) {
            return response()->json([
                'code' => 1,
                'msg' => '最少提现100元',
                'data' => null
            ]);
        }

        $user = $request->user();
        $free_free_money = intval($user->free_money * 100);

        if ($free_free_money < $withdraw_money) {
            return response()->json([
                'code' => 1,
                'msg' => '可用余额不足',
                'data' => null
            ]);
        }

        $model = new UserMoneyWithdraw();
        $model->user_id = $user->id;
        $model->org_root = $user->org_root;
        $model->org_code = $user->org_code;
        $model->comment = '';
        $model->status = UserMoneyWithdraw::PROCESSING;
        $model->money = $withdraw_money / 100;

        if ($model->save()) {
            return response()->json([
                'code' => 0,
                'msg' => '申请成功',
                'data' => $user->free_money
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '申请失败',
                'data' => null
            ]);
        }
    }

    /**
     * @return JsonResponse
     */
    public function depositProduct() {
        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'items' => ChargeProduct::where('is_disabled', 0)->orderBy('order', 'ASC')->orderBy('price', 'ASC')->limit(10)->get()
            ]
        ]);
    }

    /**
     * 充值次数
     * @param Request $request
     * @return JsonResponse
     */
    public function depositTicketBybalance(Request $request)
    {
        $model = ChargeProduct::find($request->product_id);
        if (empty($model) || $model->is_disabled == 1) {
            return response()->json([
                'code' => 1,
                'msg' => '产品已经下架',
                'data' => null
            ]);
        }

        $user = $request->user();
        if ($model->price > $user->free_money) {
            return response()->json([
                'code' => 1,
                'msg' => '账户余额不足',
                'data' => null
            ]);
        }

        $order = new Order();
        $order->orderno = Snowid::id();
        $order->user_id = $user->id;
        $order->org_root = $user->org_root;
        $order->org_code = $user->org_code;
        $order->price = $model->price;
        $order->ticket = $model->ticket;

        if ($order->save()) {
            // 使用余额进行支付
            $order->channel = 0;
            $order->status = 1;

            $user->money -= $order->price;
            $user->ticket += $order->ticket;
            $user->expired_at = date("Y-m-d H:i:s", strtotime("+1 month"));

            if ($user->save() && $order->save()) {
                ConsumeEvent::dispatch($user->id, -$order->price);
                BuyEvent::dispatch($user->id, $order->ticket);
            }

            return response()->json([
                'code' => 0,
                'msg' => '充值成功',
                'data' => null
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '订单创建失败',
                'data' => null
            ]);
        }
    }
}
